package com.heima.comment.service.Impl;

import com.heima.aliyun.GreeTextScan;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.service.CommentService;
import com.heima.comment.vos.ApCommentRepayVo;
import com.heima.comment.vos.ApCommentVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.*;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {


    @Autowired
    GreeTextScan greeTextScan;

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //伪分页
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            dto.setSize(10);
        }

        //查询所有的评论列表
        List<ApCommentRepay> commentRepaysList = mongoTemplate.find(Query.query(Criteria
                        .where("commentId").is(dto.getCommentId())
                        .and("createdTime").lt(dto.getMinDate()))
                        .limit(dto.getSize())
                        .with(Sort.by(Sort.Order.desc("createdTime")))
                , ApCommentRepay.class);

        //判断是否登录，若未登录则直接返回评论列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(commentRepaysList);
        }

        //若用户登录，则要返回点赞列表
        List<ApCommentRepayVo> apCommentRepayVoList = new ArrayList<>();

        //获取文章对应的所有评论列表id
        List<String> idList = commentRepaysList.stream().map(comment -> comment.getId()).collect(Collectors.toList());

        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria
                        .where("commentRepayId").is(idList)
                        .and("authorId").is(user.getId()))
                , ApCommentRepayLike.class);

        //遍历当前用户点赞列表 评论列表
        if (commentRepaysList != null && commentRepaysList.size() > 0 && apCommentRepayLikes != null && apCommentRepayLikes.size() > 0) {
            //forEach 遍历
            commentRepaysList.forEach(commen -> {//遍历所有文章列表id
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(commen, apCommentRepayVo);

                //遍历当前用户点赞列表
                apCommentRepayLikes.forEach(commenLikes -> {
                    if (commen.getId().equals(commenLikes.getCommentRepayId())) {
                        apCommentRepayVo.setOperation((short) 0);
                    }
                });
                apCommentRepayVoList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(apCommentRepayVoList);
        }

        return ResponseResult.okResult(commentRepaysList);
    }

    /**
     * 保存回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }

        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        //保存评论
        ApUser apUser = userFeign.findUserById(user.getId().longValue());

        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "非法用户");
        }

        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);

        mongoTemplate.save(apCommentRepay);

        //更新评论回复数量
        ApComment comment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        comment.setReply(comment.getReply()+1);
        mongoTemplate.save(comment);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //参数校验
        if (dto == null || dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取当前登录人
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 查询APUser用户信息
        Integer id = user.getId();
        ApUser apUser = userFeign.findUserById(id.longValue());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "非法用户");
        }

        //查询评论
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "暂无评论");
        }

        //判断用户是否重复点赞
        Query query = Query.query(Criteria
                .where("commentRepayId").is(dto.getCommentRepayId())
                .and("authorId").is(user.getId())
        );

        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (apCommentRepayLike != null && dto.getOperation() == 0 && apCommentRepayLike.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "重复点赞");
        }

        //保存点赞
        if (dto.getOperation().intValue() == 0) {
            if (apCommentRepayLike == null) {
                apCommentRepayLike = new ApCommentRepayLike();
                apCommentRepayLike.setAuthorId(user.getId());
                apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());

            }
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);

            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);

        } else {//取消点赞
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);

            apCommentRepay.setLikes((apCommentRepay.getLikes() + 1) < 0 ? 0 : apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepayLike);
        }

        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
